<!-- eslint-disable prefer-promise-reject-errors -->
<!-- 智能体配置 -->
<script setup lang="ts">
import type { AgentAndTrainInfo, TrainAgentInfo } from "@/common/apis/intelligent/type"
import type { EditTrainBasicInfo, SelectAgentItem } from "@/common/apis/train/type"
import { updateTaskApi } from "@/common/apis/train"
import { FormTypeEnum } from "@/common/constants/other-keys"
import SelectAgent from "@@/components/SelectAgent/index.vue"
import { Bottom, Delete, Edit, ElementPlus, Top } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { cloneDeep } from "lodash"
import { isEmpty } from "lodash-es"

interface Props {
  dialogType: FormTypeEnum
  ruleForm: EditTrainBasicInfo
  isEdit?: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(["update:ruleForm"])

const tempForm = ref<EditTrainBasicInfo | null>(null)
const dialogVisible = ref<boolean>(false)

// 处理红方智能体操作
function handleDeleteRed(row: any) {
  const index = localRuleForm.value.agent_config.red.findIndex(item => item.selectId === row.selectId)
  if (index !== -1) {
    localRuleForm.value.agent_config.red.splice(index, 1)
  }
}

function handleUpRed(row: any) {
  const index = localRuleForm.value.agent_config.red.findIndex(item => item.agent_id === row.agent_id)
  if (index > 0) {
    const temp = localRuleForm.value.agent_config.red[index - 1]
    localRuleForm.value.agent_config.red[index - 1] = row
    localRuleForm.value.agent_config.red[index] = temp
  }
}

function handleDownRed(row: any) {
  const index = localRuleForm.value.agent_config.red.findIndex(item => item.agent_id === row.agent_id)
  if (index < localRuleForm.value.agent_config.red.length - 1) {
    const temp = localRuleForm.value.agent_config.red[index + 1]
    localRuleForm.value.agent_config.red[index + 1] = row
    localRuleForm.value.agent_config.red[index] = temp
  }
}
// 处理蓝方智能体操作
function handleDeleteBlue(row: any) {
  localRuleForm.value.agent_config.blue = localRuleForm.value.agent_config.blue.filter(
    item => item !== row
  );
}

function handleUpBlue(row: any) {
  const index = localRuleForm.value.agent_config.blue.findIndex(item => item.agent_id === row.agent_id)
  if (index > 0) {
    const temp = localRuleForm.value.agent_config.blue[index - 1]
    localRuleForm.value.agent_config.blue[index - 1] = row
    localRuleForm.value.agent_config.blue[index] = temp
  }
}

function handleDownBlue(row: any) {
  const index = localRuleForm.value.agent_config.blue.findIndex(item => item.agent_id === row.agent_id)
  if (index < localRuleForm.value.agent_config.blue.length - 1) {
    const temp = localRuleForm.value.agent_config.blue[index + 1]
    localRuleForm.value.agent_config.blue[index + 1] = row
    localRuleForm.value.agent_config.blue[index] = temp
  }
}

// 选择智能体
function handleSelectAgent() {
  dialogVisible.value = true
}
// 关闭选择智能体
function handleCloseDialog() {
  dialogVisible.value = false
}
// 修改后
function isAgentInTeam(agentId: string, camp: string, trainedAgentId?: string) {
  // 检查红方
  const isInSelect = localRuleForm.value.agent_config[camp].some(agent =>
    isAgentMatch(agent, agentId, trainedAgentId)
  )
  return isInSelect
}
// 辅助函数：检查智能体是否匹配
function isAgentMatch(agent: SelectAgentItem, agentId: string, trainedAgentId?: string) {
  if (!agent) return false
  if (trainedAgentId) {
    // 如果是训练后的智能体，匹配 trained_agent_id
    return agent.trained_agent_id === trainedAgentId && agentId === agent.agent_id
  } else {
    // 如果是基础智能体，匹配 agent_id 且确保不是训练后的智能体
    return agent.agent_id === agentId && isEmpty(agent.trained_agent_id)
  }
}
// 获取智能体所在阵营
function getAgentTeam(agentId: string, trainedAgentId?: string) {
  if (localRuleForm.value.agent_config.red.some(agent =>
    isAgentMatch(agent, agentId, trainedAgentId)
  )) {
    return "red"
  }
  if (localRuleForm.value.agent_config.blue.some(agent =>
    isAgentMatch(agent, agentId, trainedAgentId)
  )) {
    return "blue"
  }
  return null
}

// 处理加入队伍
function handleJoinTeam(data: { camp: "red" | "blue", agent: AgentAndTrainInfo | TrainAgentInfo, isTrained: boolean }) {
  const { camp, agent, isTrained } = data
  let newAgent: SelectAgentItem
  if (isTrained) {
    // 验证必要字段
    if (!agent.trained_agent_id || !agent.trained_agent_name) {
      ElMessage.error("智能体信息不完整")
      return
    }
    // 检查是否已经在队伍中
    if (isAgentInTeam(agent.base_agent_id, camp, agent.trained_agent_id)) {
      ElMessage.warning(`该智能体已加入${camp === "red" ? "红" : "蓝"}方阵营`)
      return
    }
    newAgent = {
      agent_id: agent.base_agent_id,
      agent_name: agent.trained_agent_name,
      agent_describe: "",
      selectId: agent.selectId,
      agent_interval: 1,
      evolve_enable: false
    }
  } else {
    // 验证必要字段
    if (!(agent as AgentAndTrainInfo).agent_id || !(agent as AgentAndTrainInfo).agent_name) {
      ElMessage.error("智能体信息不完整")
      return
    }
    // 检查是否已经在队伍中
    if (isAgentInTeam(agent.base_agent_id, camp, undefined)) {
      ElMessage.warning(`该智能体已加入${camp === "red" ? "红" : "蓝"}方阵营`)
      return
    }
    newAgent = {
      agent_id: (agent as AgentAndTrainInfo).agent_id,
      agent_name: (agent as AgentAndTrainInfo).agent_name,
      agent_describe: (agent as AgentAndTrainInfo).agent_describe,
      agent_interval: 1,
      selectId: (agent as AgentAndTrainInfo).selectId,
      evolve_enable: false
    }
  }
  // 如果是训练后的智能体，添加训练相关信息
  if (isTrained) {
    newAgent.trained_agent_name = agent.trained_agent_name
    newAgent.trained_agent_id = agent.trained_agent_id
    newAgent.trained_agent_version = agent.trained_agent_version
    newAgent.trained_agent_reward = agent.trained_agent_reward
  }
  // 添加到对应阵营
  if (camp === "red") {
    localRuleForm.value.agent_config.red.push(newAgent)
  } else {
    localRuleForm.value.agent_config.blue.push(newAgent)
  }
}
const localRuleForm = computed({
  get: () => props.ruleForm,
  set: (newValue) => {
    emit("update:ruleForm", newValue)
  }
})

// 校验规则
function validateAgentConfig() {
  const { red, blue } = props.ruleForm.agent_config
  // 检查是否至少有一个智能体
  if (red.length === 0 && blue.length === 0) {
    return Promise.reject("请至少选择一个智能体")
  }
  // 检查是否至少有一个进化智能体
  const hasEvolveAgent = [...red, ...blue].some(agent => agent.evolve_enable)
  if (!hasEvolveAgent) {
    return Promise.reject("请至少设置一个进化智能体")
  }
  return Promise.resolve()
}

function formatter(row: any, column: any, cellValue: boolean) {
  return cellValue ? "是" : "否"
}

// 暴露验证方法给父组件
defineExpose({
  validate: async () => {
    // 智能体配置不需要特殊验证，但也要记录验证结果
    try {
      // 这里可以添加检查逻辑，例如检查是否至少添加了一个智能体
      // 如果需要有这样的业务逻辑的话
      return true
    } catch (error) {
      console.error('智能体配置验证失败:', error)
      return false
    }
  }
})

</script>

<template>
  <div class="steps-wrapper agent-setting">
    <div class="cpi-header-title">
      <SvgIcon name="info-title" />
      <span class="cpi-header-text">智能体配置</span>
    </div>
    <div class="toolbar-wrapper" :class="{ 'only-right': !isEdit && dialogType != FormTypeEnum.CREATE }"
      v-if="isEdit || dialogType == FormTypeEnum.CREATE">
      <el-button @click="handleSelectAgent" class="select-agent-btn">
        选择智能体
      </el-button>
    </div>

    <div class="agent-content">
      <div class="agent-content-item">
        <div class="cpi-header">
          <el-icon color="#FF5640" :size="18">
            <ElementPlus />
          </el-icon>
          已选红方智能体
        </div>
        <el-table ref="RedTableRef" row-key="selectId" :data="localRuleForm.agent_config.red">
          <el-table-column label="智能体名称" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.trained_agent_id ? scope.row.trained_agent_name : scope.row.agent_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.trained_agent_id ? '' : scope.row.agent_describe }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="agent_interval" align="center" label="决策周期" width="120">
            <template #default="scope">
              <el-input-number v-if="isEdit || dialogType == FormTypeEnum.CREATE"
                v-model.number="scope.row.agent_interval" :min="1" :controls="false" :precision="0" style="width: 100%"
                @change="(val: any) => (scope.row.agent_interval = Number(val))" />
              <span v-else>{{ scope.row.agent_interval }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="evolve_enable" :formatter="formatter" align="center" label="是否进化" width="100">
            <template #default="scope">
              <el-switch width="50" v-if="isEdit || dialogType == FormTypeEnum.CREATE" v-model="scope.row.evolve_enable"
                inline-prompt active-text="是" inactive-text="否" />
              <span v-else>{{ scope.row.evolve_enable ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" v-if="isEdit || dialogType == FormTypeEnum.CREATE" label="操作" width="120">
            <template #default="scope">
              <el-space>
                <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                  <el-link :underline="false" @click="handleDeleteRed(scope.row)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-link>
                </el-tooltip>
                <el-tooltip class="box-item" v-if="ruleForm.agent_config.red.length > 1 && scope.$index > 0"
                  effect="dark" content="上移" placement="top">
                  <el-link :underline="false" class="table-select-btn-item" v-throttle="() => handleUpRed(scope.row)">
                    <el-icon>
                      <Top />
                    </el-icon>
                  </el-link>
                </el-tooltip>
                <el-tooltip class="box-item"
                  v-if="ruleForm.agent_config.red.length > 1 && scope.$index < ruleForm.agent_config.red.length - 1"
                  effect="dark" content="下移" placement="top">
                  <el-link :underline="false" v-throttle="() => handleDownRed(scope.row)">
                    <el-icon>
                      <Bottom />
                    </el-icon>
                  </el-link>
                </el-tooltip>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="agent-content-item">
        <div class="cpi-header">
          <el-icon color="#409FFF" :size="18">
            <ElementPlus />
          </el-icon>
          已选蓝方智能体
        </div>
        <el-table ref="BlueTableRef" row-key="selectId" :data="localRuleForm.agent_config.blue">
          <el-table-column label="智能体名称" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.trained_agent_id ? scope.row.trained_agent_name : scope.row.agent_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="描述" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.trained_agent_id ? '' : scope.row.agent_describe }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="agent_interval" align="center" label="决策周期" width="120">
            <template #default="scope">
              <el-input-number v-if="isEdit || dialogType == FormTypeEnum.CREATE"
                v-model.number="scope.row.agent_interval" :min="1" :controls="false" :precision="0" style="width: 100%"
                @change="(val: any) => (scope.row.agent_interval = Number(val))" />
              <span v-else>{{ scope.row.agent_interval }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="evolve_enable" :formatter="formatter" align="center" label="是否进化" width="100">
            <template #default="scope">
              <el-switch width="50" v-if="isEdit || dialogType == FormTypeEnum.CREATE" v-model="scope.row.evolve_enable"
                inline-prompt active-text="是" inactive-text="否" />
              <span v-else>{{ scope.row.evolve_enable ? "是" : "否" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" v-if="isEdit || dialogType == FormTypeEnum.CREATE" label="操作" width="120">
            <template #default="scope">
              <el-space>
                <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                  <el-link :underline="false" @click="handleDeleteBlue(scope.row)">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-link>
                </el-tooltip>
                <el-tooltip class="box-item" v-if="ruleForm.agent_config.blue.length > 1 && scope.$index > 0"
                  effect="dark" content="上移" placement="top">
                  <el-link :underline="false" v-throttle="() => handleUpBlue(scope.row)">
                    <el-icon>
                      <Top />
                    </el-icon>
                  </el-link>
                </el-tooltip>
                <el-tooltip class="box-item"
                  v-if="ruleForm.agent_config.blue.length > 1 && scope.$index < ruleForm.agent_config.blue.length - 1"
                  effect="dark" content="下移" placement="top">
                  <el-link :underline="false" v-throttle="() => handleDownBlue(scope.row)">
                    <el-icon>
                      <Bottom />
                    </el-icon>
                  </el-link>
                </el-tooltip>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <SelectAgent :selected="localRuleForm.agent_config" :visible="dialogVisible" :check-agent-in-team="isAgentInTeam"
      :get-agent-team="getAgentTeam" @close-dialog="handleCloseDialog" @join-team="handleJoinTeam" />
  </div>
</template>

<style lang="scss" scoped>
.steps-wrapper {
  margin: 20px 0;
  padding: 20px;
  width: 100%;
  height: auto;
  background: #031527;
}

.agent-setting {
  .cpi-header {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 7px;
    margin-bottom: 16px;
  }

  .agent-content {
    display: flex;
    flex-direction: row;
    gap: 16px;
    margin: 16px 0;

    &-item {
      flex: 1;
      min-width: 300px;
      background-color: var(--el-bg-color);
      border-radius: 4px;
    }
  }

  .toolbar-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .toolbar-right {
      display: flex;
      gap: 12px;
    }

    &.only-right {
      justify-content: flex-end;
    }
  }
}

@media screen and (max-width: 1195px) {
  .agent-content {
    flex-direction: column !important;
  }
}
.select-agent-btn {
  width: 109px;
  height: 32px;
  background: linear-gradient(180deg, rgba(9, 109, 140, 0) 0%, #095C8C 100%);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

.cpi-header-title {
  margin-bottom: 16px;
}

.cpi-header-text {
  margin-left: 6px;
}
</style>
